package cn.hanna.springcloud.controller;

import cn.hanna.springcloud.entities.CommonResult;
import cn.hanna.springcloud.entities.Payment;
import cn.hanna.springcloud.mybl.impl.MyRoundLoadBalance;
import com.netflix.discovery.converters.Auto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author smileha
 * @create 2021-10-16 14:44
 * @description
 */
@RestController
@Slf4j
public class OrderController {

//    private String PAYMENT_URL = "http://localhost:8001";
    // 跟据应用名动态决定想谁发送请求
    private final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired  // 注意不要到错包
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate; // 用于访问Rest服务的客户端模板工具集

    @PostMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getSerialById(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/consumer/payment/getEntity/{id}")
    public CommonResult getSerialById2(@PathVariable("id") Long id){
        // 返回ResponseEntity中包含了响应信息
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        log.info("响应头信息contentType:"+entity.getHeaders().getContentType()); // 获取响应头信息
        // 是否成功响应
        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else{
            return new CommonResult(444,"响应失败",null);
        }
    }

    // 获取服务发现
    @GetMapping("/consumer/payment/discovery")
    public List getDiscoveryClient(){
        // 获取注册到eureka上的全部服务
        List<String> services = discoveryClient.getServices();
        for(String service:services){
            log.info("*************service:"+service);
        }

        // 跟据服务id获取注册实例（不区分大小写）
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance:instances){
            log.info("[serviceId="+instance.getServiceId()+",instanceId="+instance.getInstanceId()+",hostname="+instance.getHost()+",port="+instance.getPort()+",uri="+instance.getUri()+"]");
        }
        return instances;
    }

    @Autowired    // 获取自定义的轮询负载均衡实现对象
    private MyRoundLoadBalance myRoundLoadBalance;

    // 访问服务端/payment/loadbalance测试自定义负载均衡功能
    @GetMapping("/consumer/payment/lb")
    public String getBL(){
        String URI = null;
        // 获取指定服务所对应的服务器id实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances.size() == 0 || instances == null ){
            return "访问路径未注册!";
        }
        // 获取要访问的服务器路径
        ServiceInstance serviceInstance = myRoundLoadBalance.getServiceInstance(instances);
        URI = serviceInstance.getUri().toString();
        log.info(URI+"，**********这是要访问的服务器路径");
        return restTemplate.getForObject(URI + "/payment/loadbalance",String.class);
    }

    // 检验sleuth的链路监控
    @GetMapping("/consumer/payment/zipkin")
    public String checkSleuth(){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/zipkin",String.class);
    }
}
